<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/购物车.css">
</head>

<body>
    <div class="box">
        <div class="left">

        </div>
        <div class="right">
            <h2>
                购物车(<span>0</span>)
            </h2>
            <table>
                <thead>
                    <tr>
                        <th>
                            <input type="checkbox" name="" id="">全选
                        </th>
                        <th>图片</th>
                        <th>价格</th>
                        <th>数量</th>
                        <th>删除/收藏</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
                <tfoot>
                    <tr>
                        <th>
                            总价：<span>0</span> 元
                        </th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</body>

</html>
<script>
    // 保存产品数据的数组
    let list = [{ productid: 1, productsrc: 'img/pic1.png', productName: '高级办公椅', price: 100, count: 1 }, { productid: 2, productsrc: 'img/pic1.png', productName: '高级办公椅1', price: 200, count: 1 }, { productid: 3, productsrc: 'img/pic1.png', productName: '高级办公椅2', price: 300, count: 1 }, { productid: 4, productsrc: 'img/pic1.png', productName: '高级办公椅3', price: 400, count: 1 }, { productid: 5, productsrc: 'img/pic1.png', productName: '高级办公椅4', price: 500, count: 1 }, { productid: 6, productsrc: 'img/pic1.png', productName: '高级办公椅5', price: 600, count: 1 }, { productid: 7, productsrc: 'img/pic1.png', productName: '高级办公椅6', price: 700, count: 1 }]
    // 渲染数据到产品展示页面
    renderProduct()
    // 购物车数据
    let shop = { productlist: [] }
    let arr = []
    // 渲染数据到产品展示页面
    function renderProduct() {
        document.querySelector('.box .left').innerHTML = list.map((item) => {
            return `
            <div class="item">
                <div class="top">
                    <img src=${item['productsrc']} alt="">
                </div>
                    <div class="bottom">
                        <p>名称：${item['productName']}</p>
                        <p>价格：${item['price']}</p>
                        <button>加入购物车</button>
                    </div>
                </div>
            </div>
             `
        }).join(' ')
    }
    // 渲染购物车列表
    function renderShop(arr) {
        console.log(shop.productlist);
        document.querySelector('.box .right table tbody').innerHTML = shop.productlist.map((item) => {
            return `
                    <tr>
                        <td>
                            <input type="checkbox" name="" id="">
                            <span>${item['productid']}</span>
                        </td>
                        <td>
                            <img src="${item['productsrc']}" alt="">
                            <p>${item['productName']}</p>
                        </td>
                        <td>${item['price']}</td>
                        <td>
                            <span>-</span>
                            <span>1</span>
                            <span>+</span>
                        </td>
                        <td>
                            <span>删除</span>
                            /
                            <span>收藏</span>
                        </td>
                    </tr>
                `
        }).join('')



        let trEles = [...document.querySelectorAll('.box .right table tbody tr')]

        if (arr.length != 0) {
            console.log(111, arr);
            for (let i = 0; i < arr.length; i++) {
                console.log('222', trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText);
                trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText = arr[i]
            }
            for (let i = 0; i < arr.length; i++) {
                arr.shift()
                i--
            }

        }

        // 给购物车渲染总数量和总价格

        renderAddCount(trEles)
        renderPrice(trEles)



        // 给购物车列表的相关元素添加点击事件（事件委托）
        for (let i = 0; i < trEles.length; i++) {
            trEles[i].onclick = (e) => {
                // 获取点击到的商品的id
                let productid = trEles[i].querySelector('td:nth-child(1) span').innerText
                if (e.target.innerText == '+') {
                    trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerHTML = add(trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText)
                    renderCount(trEles)
                    renderPrice(trEles)
                }
                if (e.target.innerText == '-') {
                    trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerHTML = jian(trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText, productid,trEles,i)
                    renderCount(trEles)
                    renderPrice(trEles)
                }
                if (e.target.innerText == '删除') {
                    trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerHTML = shanchu(productid,trEles,i)
                    renderCount(trEles)
                    renderPrice(trEles)
                }

            }

        }

    }
    //渲染购物车总数
    function renderAddCount(trEles) {
        let sum = count(trEles)
        let countValue = Number(document.querySelector('.box .right h2 span').innerText)
        countValue = countValue == 0 ? 1 : sum
        document.querySelector('.box .right h2 span').innerText = countValue
    }
    function renderCount(trEles) {
        document.querySelector('.box .right h2 span').innerText = count(trEles)
    }
    // 渲染总价格
    function renderPrice(trEles) {
        let priceCount = 0
        for (let i = 0; i < trEles.length; i++) {
            // 获取每个商品的数量count
            // 获取每个商品的价格price
            priceCount += Number(trEles[i].querySelector('td:nth-child(3)').innerText) * Number(trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText)
        }
        document.querySelector('.box .right table tfoot tr th span').innerText = priceCount
    }

    // 给‘加入购物车’按钮添加点击事件(事件委托)
    document.querySelector('.box .left').onclick = (e) => {
        // let index=null
        // 判断点击的标签是不是按钮标签
        if (e.target.tagName == 'BUTTON') {
            // 获取所有的按钮标签,...合并成数组
            let btns = [...document.querySelectorAll('.box .left .item .bottom button')]
            // 确定点击的是哪一个按钮
            index = btns.findIndex((item) => {
                return item == e.target
            })
            let trEles = [...document.querySelectorAll('.box .right table tbody tr')]
            // 如果在购物车数组里面有同样的对象时，就直接让该代码对应的数量加1
            if (shop.productlist.indexOf(list[index]) == '-1') {

                if (shop.productlist.length == 0) {
                    shop.productlist.push(list[index])

                    // 渲染购物车列表
                    renderShop(arr)
                } else {


                    for (let i = 0; i < trEles.length; i++) {
                        let countValue = trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText
                        arr.push(countValue)
                    }

                    shop.productlist.push(list[index])
                    // 渲染购物车列表
                    renderShop(arr)

                }

            } else {

                for (let i = 0; i < trEles.length; i++) {
                    if (trEles[i].querySelector('td:nth-child(1) span').innerText == list[index]['productid']) {
                        let countValue = trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText
                        trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText = add(countValue)
                        renderCount(trEles)
                        renderPrice(trEles)
                    }

                }

            }
        }

    }

    // 购物车总数量
    function count(trEles) {
        let count = 0
        for (let i = 0; i < trEles.length; i++) {
            let sum = Number(trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText)
            count += sum
        }
        return count
    }
    // 点击加号之后，让数据加1
    function add(count) {
        count = Number(count)
        count++
        return count
    }
    // 点击减号之后，让数据减1
    function jian(count, id,trEles,trIndex) {
        count = Number(count)
        // 如果数量为1时，就删除掉相关数据
        if (count == 1) {
            shanchu(id,trEles,trIndex)
            // return
        }
        count--
        return count
    }
    // 删除整条数据
    function shanchu(id, trEles,trIndex) {
        console.log(shop.productlist.length);
        // 把和id值一样的数据删掉
        // let array = shop.productlist.filter((item) => {
        //     return item['productid'] != id
        // })
        // for (let i = 0; i < shop.productlist.length; i++) {
        //     shop.productlist.pop()
        //     i--
        // }
        // console.log(array);
        // for (let i = 0; i < array.length; i++) {
        //     shop.productlist[i]=array[i]
            
        // }
        // shop.productlist=array
        console.log(shop.productlist.length);
        if (shop.productlist.length = 0) {
            document.querySelector('.box .right h2 span').innerText = 0
            document.querySelector('.box .right table tfoot tr th span').innerText = 0
        }
        for (let i = 0; i < trEles.length; i++) {
            if (i!=trIndex) {
                let countValue = trEles[i].querySelector('td:nth-child(4) span:nth-child(2)').innerText
                arr.push(countValue) 
            }
            
        }
        renderShop(arr)
    }




</script>